package com.se.server;

import com.se.common.ConnectionType;
import com.se.common.User;
import com.se.db.DbUtils;
import com.se.exception.ConnectionExistException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器主类 - 实现TCP服务端核心逻辑
 */
public class Server {
    private static ServerSocket server = null;
    private static final Logger logger = LoggerFactory.getLogger(Server.class);
    private static boolean flag = true;
    private static final ConcurrentHashMap<String, SocketSet> connections = new ConcurrentHashMap<>();
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    /**
     * 服务器构造函数 - 启动服务并监听客户端连接
     */
    public Server(){
        DbUtils.init();
        try {
            server = new ServerSocket(ServerUtils.port);
            logger.info("服务器已启动");
            while(flag){
                Socket socket = server.accept();
                threadPool.execute(new ClientHandler(socket));
            }

        } catch (IOException e) {
            if(flag){
                logger.error("服务器启动失败: {}", e.getMessage(), e);
            }
            else {
                logger.info("服务器已关闭");
            }
        }
    }

    public static void runNewClient(Socket socket, String TYPE, User user) {
        threadPool.execute(new ClientHandler(socket, TYPE, user));
    }

    public static void addConnection(String username, Socket socket, String socketType) throws ConnectionExistException {
        SocketSet connection;
        if((connection = connections.get(username)) == null)
        {
            SocketSet ss = new SocketSet();
            ss.addSocket(socketType, socket);
            connections.put(username, ss);
            logger.info("用户已上线：: {}, {}", username, socketType);
            return;
        }
        connection.addSocket(socketType, socket);
        logger.info("建立新连接：: {}, {}", username, socketType);
    }

    public static void rmConnection(String username) {
        connections.remove(username);
    }

    public static Socket getBaseSocket(String username) {
        if(connections.get(username) == null) {
            return null;
        }
        return connections.get(username).getSocket(ConnectionType.BASE_CONNECTION);
    }

    public static void shutDown(){
        flag = false;
        try{
            if(server != null && !server.isClosed()){
                server.close();
            }
        } catch (IOException e) {
            logger.warn("服务器关闭异常: {}", e.getMessage(), e);
        }
    }
}
